let controller = null;
let chatHistory = [];
let systemPrompt = "你是一个智能AI助手，擅长编程，乐于解答问题。";

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
	// 绑定按钮事件
	document.getElementById('generate').addEventListener('click', generate);
	document.getElementById('stop').addEventListener('click', stop);
	
	// 绑定回车事件
	document.getElementById('prompt').addEventListener('keydown', (e) => {
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			generate();
		}
	});
	
	// 禁用停止按钮
	document.getElementById('stop').disabled = true;
});

// 处理markdown和katex
function processMarkdownAndKatex(content) {
	// 先处理markdown
	const html = marked.parse(content, {
		breaks: true,
		gfm: true
	});
	
	// 处理katex公式
	return html.replace(/\$\$(.*?)\$\$/g, (match, formula) => {
		try {
			return katex.renderToString(formula, {
				displayMode: true,
				throwOnError: false
			});
		} catch (e) {
			return match;
		}
	}).replace(/\$(.*?)\$/g, (match, formula) => {
		try {
			return katex.renderToString(formula, {
				displayMode: false,
				throwOnError: false
			});
		} catch (e) {
			return match;
		}
	});
}

// 添加消息到聊天窗口
function addMessage(content, isUser = false) {
	const chatContainer = document.getElementById('chat-container');
	const messageDiv = document.createElement('div');
	messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`;
	
	if (isUser) {
		// 用户消息直接显示
		messageDiv.textContent = content;
	} else {
		// AI消息需要处理markdown和katex
		messageDiv.innerHTML = processMarkdownAndKatex(content);
	}
	
	chatContainer.appendChild(messageDiv);
	chatContainer.scrollTop = chatContainer.scrollHeight;
	return messageDiv;
}

// 生成响应
async function generate() {
	const prompt = document.getElementById('prompt').value;
	const promptInput = document.getElementById('prompt');
	
	if (!prompt) {
		alert('请输入提示词');
		return;
	}

	// 更新按钮状态
	document.getElementById('generate').disabled = true;
	document.getElementById('stop').disabled = false;
	
	// 添加用户消息
	addMessage(prompt, true);
	
	// 如果是新对话，添加系统提示词
	if (chatHistory.length === 0) {
		const newPrompt = document.getElementById('system-prompt').value.trim();
		chatHistory.push({role: "system", content: newPrompt});
	}

	chatHistory.push({role: "user", content: prompt});
	
	// 清空输入框
	promptInput.value = '';
	
	// 添加助手消息占位
	const assistantMessage = addMessage('', false);

	// 准备请求参数
	const params = {
		messages: chatHistory,
		temperature: parseFloat(document.getElementById('temperature').value),
		top_p: parseFloat(document.getElementById('top_p').value),
		max_tokens: parseInt(document.getElementById('max_tokens').value),
		stream: true
	};

	try {
		controller = new AbortController();
		const response = await fetch('/v1/chat/completions', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(params),
			signal: controller.signal
		});

		// 使用 TextDecoderStream 处理流式响应
		const decoder = new TextDecoderStream();
		const reader = response.body
			.pipeThrough(decoder)
			.getReader();
		
		let assistantResponse = '';
		let buffer = '';

		while (true) {
			const {value: text, done} = await reader.read();
			if (done) break;
			
			// 将新数据添加到buffer
			buffer += text;
			
			// 按行处理数据
			while (true) {
				const newlineIndex = buffer.indexOf('\n');
				if (newlineIndex === -1) break;
				
				const line = buffer.slice(0, newlineIndex);
				buffer = buffer.slice(newlineIndex + 1);
				
				// 跳过空行
				if (!line.trim()) continue;

				// 检查是否为error
				if (line.startsWith('error:')) {
					throw new Error(line.substring(6));
				}
				
				// 检查是否为data行
				if (!line.startsWith('data:')) continue;
			
				// 检查是否结束
				if (line.endsWith('[DONE]')) break


				try {
					const obj = JSON.parse(line.substring(6));
					if(obj.finish_reason == "stop"){
						break;
					}
					const delta = obj.choices[0].delta.content;

					if (delta) {
						assistantResponse += delta;
						assistantMessage.innerHTML = processMarkdownAndKatex(assistantResponse);
						assistantMessage.scrollIntoView({behavior: "smooth", block: "end"});
					}
				} catch (e) {
					console.error('JSON解析错误:', e, '原始行:', line);
				}
			}
		}
		
		// 处理最后的buffer
		if (buffer.trim() && buffer.startsWith('data: ')) {
			try {
				const obj = JSON.parse(buffer.substring(6));
				const delta = obj.choices[0].delta.content;
				if (delta) {
					assistantResponse += delta;
					assistantMessage.innerHTML = processMarkdownAndKatex(assistantResponse);
					assistantMessage.scrollIntoView({behavior: "smooth", block: "end"});
				}
			} catch (e) {
				console.error('处理剩余buffer错误:', e);
			}
		}
		
		// 将助手回复添加到历史
		chatHistory.push({role: "assistant", content: assistantResponse});
		console.log("user:", prompt);
		console.log("assistant:", assistantResponse);
		
	} catch (err) {
		if (err.name === 'AbortError') {
			assistantMessage.textContent += '\n[已停止生成]';
		} else {
			console.error('请求错误:', err);
			assistantMessage.textContent += '\n[发生错误] ' + err.message;
		}
	} finally {
		// 恢复按钮状态
		document.getElementById('generate').disabled = false;
		document.getElementById('stop').disabled = true;
		controller = null;
	}
}

// 停止生成
function stop() {
	if (controller) {
		controller.abort();
		document.getElementById('stop').disabled = true;
	}
} 